<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退款编号" prop="refundNo">
        <el-input
          v-model="queryParams.refundNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


  <el-form-item label="退款状态" prop="refundStatus">
        <el-input
          v-model="queryParams.refundStatus"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <br/>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker clearable
          v-model="queryParams.applicationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="额外字段1" prop="extraField1">
        <el-input
          v-model="queryParams.extraField1"
          placeholder="请输入额外字段1"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="额外字段2" prop="extraField2">
        <el-input
          v-model="queryParams.extraField2"
          placeholder="请输入额外字段2"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
<hr/>

  <el-button-group style="margin-bottom: 10px;" size="large" class="ml-4">
    <el-button @click="setStatus(null)"  size="large" :type="activeStatusTab === null ? 'primary' : 'info'">全部</el-button>
    <el-button @click="setStatus('退款处理中')" size="large" :type="activeStatusTab === '退款处理中' ? 'primary' : 'info'">退款处理中</el-button>
    <el-button @click="setStatus('退款成功')" size="large" :type="activeStatusTab === '退款成功' ? 'primary' : 'info'">退款成功</el-button>
    <el-button @click="setStatus('退款失败')" size="large" :type="activeStatusTab === '退款失败' ? 'primary' : 'info'">退款失败</el-button>
  </el-button-group>





    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:recordservice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:recordservice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:recordservice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:recordservice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordserviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="退款编号" align="center" prop="refundNo" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="退款金额" align="center" prop="refundAmount" />
      <el-table-column label="申请人" align="center" prop="sysUser.nickName" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款时间" align="center" prop="refundTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.refundTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="refundOrderStatus">
        <template #default="scope">
          <dict-tag :options="lekang_orderstatus" :value="scope.row.refundOrderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="退款状态" align="center" prop="refundStatus">
        <template #default="scope">
          <dict-tag :options="lekang_orderrefundstatus" :value="scope.row.refundStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:recordservice:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:recordservice:remove']">删除</el-button> -->
            <el-button link type="primary"  @click="handleView(scope.row)" >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退款管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordserviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退款编号" prop="refundNo">
          <el-input v-model="form.refundNo" placeholder="请输入退款编号" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="申请人" prop="applicant">
          <el-input v-model="form.applicant" placeholder="请输入申请人" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker clearable
            v-model="form.applicationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="退款时间" prop="refundTime">
          <el-date-picker clearable
            v-model="form.refundTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择退款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="refundOrderStatus">
          <el-radio-group v-model="form.refundOrderStatus">
            <el-radio
              v-for="dict in lekang_orderstatus"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款状态" prop="refundStatus">
          <el-radio-group v-model="form.refundStatus">
            <el-radio
              v-for="dict in lekang_orderrefundstatus"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="form.refundReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="退款渠道" prop="refundChannel">
          <el-input v-model="form.refundChannel" placeholder="请输入退款渠道" />
        </el-form-item>
        <el-form-item label="退款方式" prop="refundMethod">
          <el-input v-model="form.refundMethod" placeholder="请输入退款方式" />
        </el-form-item>
        <el-form-item label="失败状态码" prop="failureStatusCode">
          <el-input v-model="form.failureStatusCode" placeholder="请输入失败状态码" />
        </el-form-item>
        <el-form-item label="失败原因" prop="failureReason">
          <el-input v-model="form.failureReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看退款记录对话框 -->
    <el-dialog title="查看退款记录" v-model="viewDialogVisible" width="600px" append-to-body class="refund-dialog" :show-close="false">
      <div class="view-container">
        <div class="info-item">
          <span class="label">退款编号：</span>
          <span class="value">{{ currentRecord.refundNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ currentRecord.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单状态：</span>
          <span class="value">{{ getOrderStatusText(currentRecord.refundOrderStatus) }}</span>
        </div>
        <div class="info-item">
          <span class="label">退款状态：</span>
          <span class="value refund-status" :style="getRefundStatusStyle(currentRecord.refundStatus)">{{ getStatusText(currentRecord.refundStatus) }}</span>
        </div>
        <div class="info-item">
          <span class="label">申请人：</span>
          <span class="value">{{ currentRecord.applicantName || currentRecord.sysUser?.nickName || currentRecord.applicant }}</span>
          <span v-if="currentRecord.applicantType === '后台用户'" class="applicant-type">后台用户</span>
        </div>
        <div class="info-item">
          <span class="label">申请时间：</span>
          <span class="value">{{ parseTime(currentRecord.applicationTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">退款原因：</span>
          <span class="value">{{ currentRecord.refundReason }}</span>
        </div>
        <div class="info-item">
          <span class="label">退款渠道：</span>
          <span class="value">{{ currentRecord.refundChannel }}</span>
        </div>
        <div class="info-item">
          <span class="label">退款方式：</span>
          <span class="value">{{ currentRecord.refundMethod }}</span>
        </div>
        
        <!-- 退款失败时显示的内容 -->
        <template v-if="currentRecord.refundStatus === 'refund_failed'">
          <div class="info-item">
            <span class="label">失败状态码：</span>
            <span class="value">{{ currentRecord.failureStatusCode }}</span>
          </div>
          <div class="info-item">
            <span class="label">失败原因：</span>
            <span class="value">{{ currentRecord.failureReason }}</span>
          </div>
        </template>
        
        <!-- 退款成功时显示的内容 -->
        <template v-if="currentRecord.refundStatus === 'refund_success'">
          <div class="info-item">
            <span class="label">退款时间：</span>
            <span class="value">{{ parseTime(currentRecord.refundTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">退款金额：</span>
            <span class="value">{{ currentRecord.refundAmount }} 元</span>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.view-container {
  padding: 10px 0;
}
.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.label {
  width: 100px;
  font-weight: 500;
  color: #606266;
}
.value {
  flex: 1;
  color: #303133;
}
/* 使用内联样式和更直接的选择器 */
  .applicant-type {
    background-color: #8B4513;
    color: #fff;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 8px;
    display: inline-block;
  }
  
  .refund-status {
    font-weight: 500;
  }
</style>
  
  <!-- 全局样式，不受scoped限制 -->
  <style>
  /* 退款记录对话框标题灰色背景 */
  .refund-dialog .el-dialog__header {
    background-color: #f5f7fa !important;
    padding: 15px 20px !important;
    margin: 0 !important;
  }
  
  .refund-dialog .el-dialog__title {
    color: #606266 !important;
    font-weight: 500 !important;
  }
  
  .refund-dialog .el-dialog__body {
    padding: 20px !important;
  }
  </style>
  
  <script setup name="Recordservice">
import { listRecordservice, getRecordservice, delRecordservice, addRecordservice, updateRecordservice } from "@/api/system/recordservice"

const { proxy } = getCurrentInstance()
const { lekang_orderrefundstatus, lekang_orderstatus } = proxy.useDict('lekang_orderrefundstatus', 'lekang_orderstatus')

// 查看弹窗相关
const viewDialogVisible = ref(false)
const currentRecord = ref({})

const recordserviceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    refundNo: null,
    orderNo: null,
    applicant: null,
    applicationTime: null,
    extraField1: null,
    extraField2: null,
    nickname: null,
    refundStatus: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询退款管理列表 */
function getList() {
  loading.value = true
  listRecordservice(queryParams.value).then(response => {
    recordserviceList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log(response);
    
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    refundNo: null,
    orderNo: null,
    refundAmount: null,
    applicant: null,
    applicationTime: null,
    refundTime: null,
    refundOrderStatus: null,
    refundStatus: null,
    refundReason: null,
    refundChannel: null,
    refundMethod: null,
    failureStatusCode: null,
    failureReason: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("recordserviceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加退款管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRecordservice(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改退款管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordserviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecordservice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecordservice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 查看按钮操作 */
function handleView(row) {
  // 尝试从表格行数据中获取申请人名称，如果表格中已经显示了用户名
  const rowApplicantName = typeof row === 'object' && row.sysUser?.nickName
  getRecordservice(row.id).then(response => {
    const record = response.data
    // 如果API返回的记录中没有用户信息但表格中有，则使用表格中的数据
    if (rowApplicantName && (!record.sysUser || !record.sysUser.nickName)) {
      record.applicantName = rowApplicantName
    }
    currentRecord.value = record
    viewDialogVisible.value = true
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除退款管理编号为"' + _ids + '"的数据项？').then(function() {
    return delRecordservice(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/recordservice/export', {
    ...queryParams.value
  }, `recordservice_${new Date().getTime()}.xlsx`)
}

/** 获取状态样式类 */
function getStatusClass(status) {
  switch (status) {
    case 'refund_failed':
      return 'refund-failed'
    case 'refund_processing':
      return 'refund-processing'
    case 'refund_success':
      return 'refund-success'
    default:
      return ''
  }
}

/** 获取退款状态动态样式 - 直接返回内联样式对象 */
function getRefundStatusStyle(status) {
  // 兼容中英文枚举
  switch (status) {
    case 'refund_success':
    case '退款成功':
      return { color: '#67c23a' }
    case 'refund_failed':
    case '退款失败':
      return { color: '#f56c6c' }
    case 'refund_processing':
    case '退款处理中':
      return { color: '#8B4513' }
    default:
      return {}
  }
}

/** 获取状态文本 */
function getStatusText(status) {
  const dict = lekang_orderrefundstatus.value.find(item => item.value === status)
  return dict ? dict.label : status
}

/** 获取订单状态文本 */
function getOrderStatusText(status) {
  const dict = lekang_orderstatus.value.find(item => item.value === status)
  return dict ? dict.label : status
}

// 状态筛选当前激活项（null 表示全部）
const activeStatusTab = ref(null)

// 设置状态并使用现有搜索方法查询
function setStatus(status) {
  activeStatusTab.value = status
  queryParams.value.refundStatus = status
  handleQuery()
}

getList()
</script>


<style scoped>

</style>